import {
  KeywordModel
} from "../../models/keyword.js";
import {
  BookModel
} from "../../models/book.js";
import {
  paginationBev
} from "../behaviors/pagination.js";

var keywordModel = new KeywordModel();
var bookModel = new BookModel();

Component({

  behaviors: [paginationBev],

  /**
   * 组件的属性列表
   */
  properties: {
    more: {
      type: String,
      observer: 'loadMore'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    q: '',
    historyWords: [],
    hotWords: [],
    isLoadingMore: false,
    searching: false,
    loadingCenter: false
  },

  attached() {
    this.setData({
      historyWords: keywordModel.getHistory()
    });
    keywordModel.getHot().then(res => {
      this.setData({
        hotWords: res.data.hot
      });
    })
  },

  /**
   * 组件的方法列表
   */
  methods: {

    loadMore: function(event) {
      if (this.data.isLoadingMore) return;
      if (!this.data.q) return;
      if (!this.hasMore()) return;
      this._setLoadingMore();
      bookModel.search(this.getCurrentStart(), this.data.q).then(res => {
        this.setMoreData(res.data.books);
        this._cancelLoadingMore();
      }, error => {
        this._cancelLoadingMore();
      })
    },

    onCancel: function(event) {
      this.initialize();
      this.triggerEvent("cancel", {}, {})
    },

    onDelete: function(event) {
      this.initialize();
      this._closeResult();
    },

    onConfirm: function(event) {
      this._showLoadingCenter();
      const word = event.detail.value || event.detail.text;
      this._showResult(word);
      bookModel.search(0, word).then(res => {
        this._hideLoadingCenter();
        keywordModel.addToHistory(word);
        this.setMoreData(res.data.books);
        this.setTotal(res.data.total);
      })
    },

    _showLoadingCenter() {
      this.setData({
        loadingCenter: true
      })
    },

    _hideLoadingCenter() {
      this.setData({
        loadingCenter: false
      })
    },

    _showResult(word) {
      this.setData({
        searching: true,
        q: word
      })
    },

    _closeResult() {
      this.setData({
        searching: false,
        q: ''
      })
    },

    _setLoadingMore() {
      this.setData({
        isLoadingMore: true
      });
    },

    _cancelLoadingMore() {
      this.setData({
        isLoadingMore: false
      });
    },

  }

})